package com.rockcent.message.localController;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateFormatUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.MD5Utils;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.lib.domain.SysMessage;
import com.rockcent.mall.lib.domain.SysMessageUser;
import com.rockcent.mall.lib.domain.enumclass.SysMessageStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageType;
import com.rockcent.mall.lib.domain.enumclass.TerminalType;
import com.rockcent.mall.lib.dto.SysMessageDto;
import com.rockcent.message.Routes;
import com.rockcent.service.AuthUserResourceSrv;
import com.rockcent.service.SysMessageSrv;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息处理中心
 * Created by zhangjh on 2017/5/23.
 */
@RestController
@RequestMapping(value = Routes.API_LOCAL_PREFIX)
public class SysMessageConfigController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(SysMessageConfigController.class);

    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;


    @Autowired
    private AuthUserResourceSrv authUserResourceSrv;

    @Autowired
    private SysMessageSrv sysMessageSrv;

    private static final String destination = "/message";

    /**
     * @param request
     * @param messageDto
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping(value = Routes.PUSHMSG_TO_SERVER, method = RequestMethod.POST)
    public JsonResult pushMsg(HttpServletRequest request, @RequestBody SysMessageDto messageDto) {
        Long userId = messageDto.getUserId();
        Long mallId = messageDto.getMallId();
        Long merchantId = messageDto.getMerchantId();
        SysMessage bean = new SysMessage();
        RBeanUtils.copyProperties(messageDto, bean);
        log.info("======================>messageDto:{}", messageDto);
        bean.setType(SysMessageType.valueOf(messageDto.getType()));
        String terminalType = messageDto.getTerminalType();
        bean.setTerminalType(TerminalType.valueOf(terminalType));

        RestDoing doing = jsonResult -> {
            List<Long> userids = new ArrayList<Long>();

            //
//            String useridStr = StringUtils.join(userids.toArray(), ",");
            if (null != userId) {
                userids.add(userId);
            } else {

                //拥有权限前端URL的用户
                String frontendResourceUrl = messageDto.getFrontendResourceUrl();
                userids = authUserResourceSrv.findAuthUserIdByUrl(null, frontendResourceUrl);
                log.info("======================>以下用户:{},拥用该url:[{}]的权限,", userids, frontendResourceUrl);
                //
                List<Long> allUserIdOfPlatform = authUserResourceSrv.findAuthUserIdByMalMerchantIdAndIsSuperAdmin(mallId, merchantId, Whether.NO);
                log.info("======================>该平台/商户下的普通用户:{}", allUserIdOfPlatform);
                userids.retainAll(allUserIdOfPlatform);

                //超级管理员
                List<Long> superAdminUserIds = authUserResourceSrv.findAuthUserIdByMalMerchantIdAndIsSuperAdmin(mallId, merchantId, Whether.YES);
                log.info("======================>该平台/商户下的超级管理员用户:{}", superAdminUserIds);
                userids.addAll(superAdminUserIds);

            }
            log.info("======================>发送消息:[{}]:给以下用户:{}", bean.getContent(), userids);

            if (null != userids) {
                SysMessage messageDB = sysMessageSrv.saveSysMessage(bean);
                String content = messageDB.getContent();
                Long msgId = messageDB.getId();
                for (Long userid : userids) {

                    //通知在线的人
                    Long destinationTerminalId = 0L;
                    if (terminalType.equals(TerminalType.MERCHANT.toString())) {
                        destinationTerminalId = merchantId;
                    } else if (terminalType.equals(TerminalType.MALL.toString())) {
                        destinationTerminalId = mallId;
                    }

                    String userIdStr = String.valueOf(userid);
                    //保存数据库
                    SysMessageUser sysMessageUser = new SysMessageUser();
                    sysMessageUser.setMsgId(msgId);
                    sysMessageUser.setUserId(userid);
                    sysMessageUser.setStatus(SysMessageStatus.UNREAD);
                    sysMessageUser.setDestinationTerminalId(destinationTerminalId);
                    sysMessageUser = sysMessageSrv.saveSysMessageUser(sysMessageUser);
                    log.info("======================>保存的用户消息sysMessageUser:{}", sysMessageUser);

                    messageDto.setId(messageDB.getId());
                    messageDto.setMsgUserId(sysMessageUser.getId());
//                    messageDto.setDateCreated(new Date());
                    messageDto.setNotifyDate(DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT2));
                    messageDto.setType(messageDB.getType().toString());


                    //长连接url
                    String url = userIdStr + "_" + destinationTerminalId + "_" + terminalType;

                    log.info("======================>推送消息长连接URL:{},messageDto:{}", url, messageDto);
                    url = MD5Utils.encript(url);
                    simpMessagingTemplate.convertAndSendToUser(url, destination, messageDto);
                }
            }
        };
        return doing.go(request, log);
    }


}
